<template>
	<view class="page_container">
		<view class="join_group_container">
			<button @click="joinGroup('game_39')">加入39群</button>
			<button @click="joinGroup('test_01')">加入test01群</button>
			<button @click="joinGroup('test_02')">加入test02群</button>
		</view>
		<view class="conversation_list">
			<view class="conversation_item" v-for="item in conversations" :key="item.conversationID"
				@click="chat(item)">
				<view class="conversation_item_avatar">
					<image :src="item.faceURL" mode="widthFix"></image>
				</view>
				<view class="conversation_item_info">
					<view class="conversation_item_name">
						{{ item.showName }}
					</view>
					<view class="conversation_item_last_message" v-if="item.conversationType == '1'">
						<template v-if="item.latestMsg.contentType == 2101">
							一条撤回信息
						</template>
						<template v-else-if="item.latestMsg.contentType == 110">
							{{ item.latestMsg.customElem.data }}
						</template>
						<template v-else>
							{{ item.latestMsg.textElem.content }}
						</template>
					</view>
					<view class="conversation_item_last_message" v-if="item.conversationType == '3'">
						<template v-if="item.latestMsg.contentType == 1508">
							某成员离开群组
						</template>
						<template v-else-if="item.latestMsg.contentType == 1510">
							{{ JSON.parse(item.latestMsg.notificationElem.detail).entrantUser.nickname }}加入群组
						</template>
						<template v-else-if="item.latestMsg.contentType == 1504">
							{{ JSON.parse(item.latestMsg.notificationElem.detail).quitUser.nickname }}退出群组
						</template>
						<template v-else-if="item.latestMsg.contentType == 1511">
							解散群通知
						</template>
						<template v-else>
							{{ item.latestMsg.textElem.content }}
						</template>
					</view>
				</view>
				<view class="last_part">
					<view class="conversation_item_time">
						{{ humanFormatTime(item.latestMsgSendTime) }}
					</view>
					<view class="conversation_item_unread_count">
						{{ item.unreadCount }}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import dayjs from 'dayjs';

const conversations = ref([]);

onLoad(() => {
	let attempts = 0;
	const getConversationListSplit = async () => {
		const { data: loginStatus } = await uni.$openIM.getLoginStatus();
		if (3 == loginStatus) {
			try {
				const { data: conversationList } = await uni.$openIM.getConversationListSplit({
					offset: 0,
					count: 20,
				});
				// 调用成功
				conversations.value = conversationList.filter(item => item.latestMsg).map(item => {
					if (item.latestMsg) {
						item.latestMsg = JSON.parse(item.latestMsg)
						console.log('item.latestMsg', item.latestMsg)
					}
					return item;
				});
			} catch ({ errCode, errMsg }) {
				console.log('Failed to get conversation list', errCode, errMsg);
			}
		} else {
			attempts++;
			if (attempts < 3) {
				setTimeout(getConversationListSplit, 2000);
			} else {
				console.log('无法得到对话list');
			}
		}
	};

	getConversationListSplit();
});

onMounted(() => {
	uni.$emitter.on('OnConversationChanged', (data) => {
		console.log('index page 收到会话变更事件')
		dealNewMessage(data)
	})
	uni.$emitter.on('OnNewConversation', (data) => {
		console.log('index page 收到新会话事件', data)
		dealNewMessage(data)
	})
})

function dealNewMessage(data) {
	let newConversations = data.data;
	for (let i = 0; i < newConversations.length; i++) {
		const item = newConversations[i];
		const index = conversations.value.findIndex(conversation => conversation.conversationID === item.conversationID);
		if (index !== -1) {
			conversations.value.splice(index, 1);
		}
		item.latestMsg = JSON.parse(item.latestMsg)
		conversations.value.unshift(item);
	}
}

onUnmounted(() => {
	uni.$emitter.off('OnConversationChanged');
	uni.$emitter.off('OnNewConversation');
})

function chat(item) {
	if (item.conversationType == '1') {
		uni.navigateTo({
			url: `/pages/index/private?conversationID=${item.conversationID}`
		});
	} else if (item.conversationType == '3') {
		uni.navigateTo({
			url: `/pages/index/group?conversationID=${item.conversationID}`
		});
	}
}

function joinGroup(groupID) {
	uni.$openIM.joinGroup({
		groupID: groupID,
		reqMsg: '',
		joinSource: 4
	}).then(() => {
		// 调用成功
		console.log('加入群组成功')
	}).catch(({ errCode, errMsg }) => {
		// 调用失败
		console.log('加入群组失败', errCode, errMsg)
	});
}

function humanFormatTime(timestamp) {
	const today = dayjs().startOf('day');
	const date = dayjs(timestamp);

	if (date.isSame(today, 'day')) {
		// 如果是今天
		return `今天 ${date.format('HH:mm')}`;
	} else if (date.isSame(today.subtract(1, 'day'), 'day')) {
		// 如果是昨天
		return `昨天 ${date.format('HH:mm')}`;
	} else {
		// 如果是前天或更早
		return date.format('MM/DD HH:mm');
	}
}
</script>

<style lang="scss" scoped>
.page_container {
	padding: 24rpx;
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	justify-content: flex-start;

	.join_group_container {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
		gap: 24rpx;
	}

	.conversation_list {
		margin-top: 24rpx;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: stretch;
		justify-content: flex-start;
		gap: 24rpx;

		.conversation_item {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: flex-start;

			.conversation_item_avatar {
				image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
				}
			}

			.conversation_item_info {
				margin-left: 20rpx;
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				justify-content: flex-start;
			}

			.last_part {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				justify-content: flex-end;
			}
		}
	}
}
</style>
